package views

import (
	"strconv"
	"net/http"
	"appengine"
	"appengine/datastore"
	"mdbook/model/post"
)


// 浏览网站
func ReservePageHandler(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	model := newModel(req, "404", nil)
	view, _ := renderView(req, "reserve.tpl", model)
	w.Write(view)
}

func PostHandler(w http.ResponseWriter, req *http.Request) {
	query := req.URL.Query()
	ver, _ := strconv.ParseInt(query.Get("ver"), 10, 64)
	raw := query.Get("raw")
	ctx := appengine.NewContext(req)
	if path, err := post.GetPath(req.URL.Path, ctx); err == nil && path.NewPath != "" {
		ctx.Errorf("%v, %v", err, path)
		http.Redirect(w, req, path.NewPath, 301)
		return
	}
	p, err := post.Get(req.URL.Path, ver, ctx)
	if err != nil {
		if err == datastore.ErrNoSuchEntity {
			render404(w, req, req.URL.Path)
			return
		}
		renderError(w, req, err)
		return
	}
	if raw == "yes" {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.Write([]byte(p.Content))
		return
	}
	p.ParseHTML()
	model := newModel(req, "", p)
	view, err := renderView(req, "post.tpl", model)
	if err != nil {
		ctx.Errorf("%v", err)
		renderError(w, req, err)
		return
	}
	w.Write(view)
}

////////////////
/*
// Shows the welcome screen. This might actually be the blog itself.
func homeHandler(w http.ResponseWriter, r *http.Request) {
	page := cache.getCachedPage(r.URL.RequestURI())
	if page == nil {
		post := getNewestBlogPost()
		page = getPage("templates/blog.html", post)
		cache.putCachedPage(r.URL.RequestURI(), page)
	}
	//fmt.Fprintf(w, page)
	w.Write(page)
}
*/

